﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using LabMS.BLL;
using System.Text.RegularExpressions;

namespace LabMS.Web.PersonalProject
{
    public partial class EditPersonalProject : Base.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            strPageUserType.Add("student");
            if (Request.QueryString["ProjectID"] == null)
            {
                Common.JShelper.JSAlert(Page, "err", "参数错误!");
                return;
            }
            int ProjectID = 0;
            if (!int.TryParse(Request.QueryString["ProjectID"], out ProjectID))
            {
                Common.JShelper.JSAlert(Page, "err", "参数错误!");
                return;
            }
            if (!IsPostBack)
            {
                //绑定实验室
                LabDropdownlist();
                BindData(ProjectID);
            }
            ApplyTimeMin.Attributes.Add("onclick", "d.showMoreDay = false;d.show(this);");
            ApplyTimeMin.Attributes.Add("readOnly", "-1");
            ApplyTimeMax.Attributes.Add("onclick", "d.showMoreDay = false;d.show(this);");
            ApplyTimeMax.Attributes.Add("readOnly", "-1");
        }

        //绑定所属实验室
        protected void LabDropdownlist()
        {
            LabMS.BLL.Lab lab = new LabMS.BLL.Lab();
            List<LabMS.Model.Lab> ParLab = new List<LabMS.Model.Lab>();
            List<LabMS.Model.Lab> SonLab = new List<LabMS.Model.Lab>();
            List<LabMS.Model.Lab> LabTemp = new List<LabMS.Model.Lab>();

            ParLab = lab.GetModelList("Lab_ParentID is null");
            SonLab = lab.GetModelList("Lab_ParentID is not null");
            LabTemp = lab.GetModelList("Lab_ParentID is null");

            int count = ParLab.Count, count1 = SonLab.Count;
            for (int i = 0; i < count; i++)
            {
                int ID = ParLab[i].ID;
                int m = 0;
                for (int j = 0; j < count1; j++)
                {
                    LabMS.Model.Lab labModel = new LabMS.Model.Lab();
                    int ParentID = int.Parse(SonLab[j].Lab_ParentID.ToString());

                    if (ParentID == ID)
                    {
                        labModel.ID = SonLab[j].ID;
                        labModel.Lab_Name = "|-" + SonLab[j].Lab_Name;
                        LabTemp.Insert(i + m + 1, labModel);
                        m++;
                    }
                }
            }
            ddlApplyLab.DataSource = LabTemp;
            ddlApplyLab.DataBind();
            ListItem item = new ListItem("无", "0");
            ddlApplyLab.Items.Insert(0, item);
        }

        //绑定数据
        protected void BindData(int ProjectID)
        {
            //绑定基本信息
            LabMS.BLL.PersonalProject project = new LabMS.BLL.PersonalProject();
            LabMS.Model.PersonalProject projectinfo = new LabMS.Model.PersonalProject();

            projectinfo = project.GetModel(ProjectID);
            ProjectName.Text = projectinfo.ProjectName;
            PlanHours.Text = projectinfo.PlanHours.ToString();
            ddlApplyLab.SelectedValue = projectinfo.AppcationLabID.ToString();
            if (!string.IsNullOrEmpty(projectinfo.ApplicationStartTime.ToString()))
            {
                ApplyTimeMin.Text = projectinfo.ApplicationStartTime.Value.ToShortDateString();
            }
            if (!string.IsNullOrEmpty(projectinfo.ApplicationEndTime.ToString()))
            {
                ApplyTimeMax.Text = projectinfo.ApplicationEndTime.Value.ToShortDateString();
            }
            Contactor.Text = projectinfo.Contactor ;
            ContactorClass.Text = projectinfo.ContactorClass;
            ContactEmail.Text = projectinfo.ContactorEmail;
            ContactPhone.Text = projectinfo.ContactorPhone;
            Teacher.Text = projectinfo.Teacher;
            TeacherTitle.Text = projectinfo.TeacherTitle;
            TeacherEmail.Text = projectinfo.TeacherEmail;
            TeacherPhone.Text = projectinfo.TeacherPhone;
            ApplyReason.Text = projectinfo.ApplicationReason;

            //绑定申请人
            ExtendBLL.PersonalProject applicant = new ExtendBLL.PersonalProject();
            List<ExtendModule.StudentAndOther> applicantinfo = new List<ExtendModule.StudentAndOther>();

            string strWhere = " pa.PersonalProjID = " + ProjectID;
            applicantinfo = applicant.GetStudentInfoList(strWhere);
            #region 绑定申请人列表
            string strHTML0 = "<table  id='applicantlist' border='1' class='infoTable' style='width: 185px; border-collapse: collapse;'>";
            strHTML0 += "<thead>";
            strHTML0 += "<tr class='header'>";
            strHTML0 += "<td class='none'>";
            strHTML0 += "ID";
            strHTML0 += "</td>";

            strHTML0 += "<td>";
            strHTML0 += "学号";
            strHTML0 += "</td>";

            strHTML0 += "<td>";
            strHTML0 += "姓名";
            strHTML0 += "</td>";
            strHTML0 += "<td>";
            strHTML0 += "";
            strHTML0 += "</td>";
            strHTML0 += "</tr>";
            strHTML0 += "</thead>";
            strHTML0 += "<tbody>";
            tb_StudentIDs.Text = "";
            foreach (ExtendModule.StudentAndOther s in applicantinfo)
            {
                if (tb_StudentIDs.Text == "")
                {
                    tb_StudentIDs.Text += s.ID.ToString();
                }
                else
                {
                    tb_StudentIDs.Text += "," + s.ID.ToString();
                }
                strHTML0 += "<tr>";
                strHTML0 += "<td class='none'>";
                strHTML0 += s.ID.ToString();
                strHTML0 += "</td>";
                strHTML0 += "<td>";
                strHTML0 += s.Student_Code;
                strHTML0 += "</td>";
                strHTML0 += "<td>";
                strHTML0 += s.Student_Name;
                strHTML0 += "</td>";
                strHTML0 += "<td>";
                strHTML0 += "<a>删除</a>";
                strHTML0 += "</td>";
                strHTML0 += "</tr>";
            }
            strHTML0 += "</tbody>";
            strHTML0 += "</table>";
            studentlist.Text = strHTML0;
            tblistEmpty.Value = "0";
            #endregion

            //绑定低耗品和仪器
            LabMS.BLL.PersonalProjConsume projectconsume = new LabMS.BLL.PersonalProjConsume();
            List<LabMS.Model.PersonalProjConsume> projectequipinfo = new List<LabMS.Model.PersonalProjConsume>();
            List<LabMS.Model.PersonalProjConsume> projectlowconsumeinfo = new List<LabMS.Model.PersonalProjConsume>();

            #region 绑定仪器
            //仪器
            string strWhere2 = " EquipType=1 and PersonalProjID=" + ProjectID;
            projectequipinfo = projectconsume.GetModelList(strWhere2);

            string strHTML = "<table  id='tableEquip' border='1' class='infoTable' style='border-collapse: collapse;'>";
            strHTML += "<thead>";
            strHTML += "<tr class='header'>";
            strHTML += "<td style='display:none'>";
            strHTML += "编号";
            strHTML += "</td>";

            strHTML += "<td>";
            strHTML += "名称";
            strHTML += "</td>";

            strHTML += "<td>";
            strHTML += "数量";
            strHTML += "</td>";

            strHTML += "<td>";
            strHTML += "备注";
            strHTML += "</td>";

            strHTML += "<td>";
            strHTML += "";
            strHTML += "</td>";

            strHTML += "</tr>";
            strHTML += "</thead>";
            strHTML += "<tbody>";
            tb_EIndex.Value = projectequipinfo.Count.ToString();

            for (int i = 0; i < projectequipinfo.Count; i++)
            {
                strHTML += "<tr>";
                strHTML += "<td style='display:none'>";
                strHTML += "<input type='text' id='code" + i + "'/>";
                strHTML += "</td>";
                strHTML += "<td>";
                strHTML += "<input style='width:40px;' value='" + projectequipinfo[i].EquipName + "' name='name" + i + "' id='name" + i + "' type='text' /><input  onclick=OpenEditWin2('../CommonPage/consumselectlist.aspx?location=@ALL@&Type=yiqi',500,400,'code" + i + "','name" + i + "'); type='button' class='button' value='...' /> ";
                strHTML += "</td>";
                strHTML += "<td>";
                strHTML += "<input style='width:30px;' value='" + projectequipinfo[i].EquipNum + "' name='num" + i + "' id='num" + i + "' type='text' />"; 
                strHTML += "</td>";
                strHTML += "<td>";
                strHTML += "<input style='width:50px;' value='" + projectequipinfo[i].Introduction + "' name='intro" + i + "' id='intro" + i + "' type='text' />";
                strHTML += "</td>";
                strHTML += "<td>";
                strHTML += "<a>删除</a>";
                strHTML += "</td>";
                strHTML += "</tr>";
            }    
            strHTML += "</tbody>";
            strHTML += "</table>";
            lbEquip.Text += strHTML;
            #endregion
            #region 绑定低耗品
            //低耗品
            string strWhere3 = " EquipType=2 and PersonalProjID=" + ProjectID;
            projectlowconsumeinfo = projectconsume.GetModelList(strWhere3);

            string strHTML2 = "<table  id='tableConsump' border='1' class='infoTable' style='border-collapse: collapse;'>";
            strHTML2 += "<thead>";
            strHTML2 += "<tr class='header'>";
            strHTML2 += "<td style='display:none'>";
            strHTML2 += "编号";
            strHTML2 += "</td>";

            strHTML2 += "<td>";
            strHTML2 += "名称";
            strHTML2 += "</td>";

            strHTML2 += "<td>";
            strHTML2 += "数量";
            strHTML2 += "</td>";

            strHTML2 += "<td>";
            strHTML2 += "备注";
            strHTML2 += "</td>";

            strHTML2 += "<td>";
            strHTML2 += "";
            strHTML2 += "</td>";

            strHTML2 += "</tr>";
            strHTML2 += "</thead>";
            strHTML2 += "<tbody>";

            tb_ConsumpIndex.Value = projectlowconsumeinfo.Count.ToString();

            for (int i = 0; i < projectlowconsumeinfo.Count; i++)
            {
                strHTML2 += "<tr>";
                strHTML2 += "<td style='display:none'>";
                strHTML2 += "<input type='text'id='consumpcode" + i + "'/>";
                strHTML2 += "</td>";
                strHTML2 += "<td>";
                strHTML2 += "<input style='width:40px;' value='" + projectlowconsumeinfo[i].EquipName + "' name='consumpname" + i + "' id='consumpname" + i + "' type='text' /><input  onclick=OpenEditWin3('../CommonPage/consumselectlist.aspx?location=@ALL@&Type=xiaohaopin',500,400,'consumpcode" + i + "','consumpname" + i + "'); type='button' class='button' value='...' /> ";
                strHTML2 += "</td>";
                strHTML2 += "<td>";
                strHTML2 += "<input style='width:30px;' value='" + projectlowconsumeinfo[i].EquipNum + "' name='consumpnum" + i + "' id='consumpnum" + i + "' type='text' />";
                strHTML2 += "</td>";
                strHTML2 += "<td>";
                strHTML2 += "<input style='width:50px;' value='" + projectlowconsumeinfo[i].Introduction + "' name='consumpintro" + i + "' id='consumpintro" + i + "' type='text' />";
                strHTML2 += "</td>";
                strHTML2 += "<td>";
                strHTML2 += "<a>删除</a>";
                strHTML2 += "</td>";
                strHTML2 += "</tr>";
            }
            strHTML2 += "</tbody>";
            strHTML2 += "</table>";
            lbConsump.Text += strHTML2;
            #endregion
        }

        //保存
        protected void btnSave_Click(object sender, EventArgs e)
        {
            #region 验证
            if (string.IsNullOrEmpty(ProjectName.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "项目名称不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(PlanHours.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "计划学时不能为空!");
                return;
            }
            int hour = 0;
            if (!int.TryParse(PlanHours.Text.Trim(), out hour))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "计划学时只能输入数字!");
                return;
            }
            if (ddlApplyLab.SelectedValue.ToString().Equals("0"))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "申请实验室不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(ApplyTimeMin.Text.Trim()) || string.IsNullOrEmpty(ApplyTimeMax.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "申请时间不能为空!");
                return;
            }
            else
            {
                if (Convert.ToDateTime(ApplyTimeMin.Text.Trim()) > Convert.ToDateTime(ApplyTimeMax.Text.Trim()))
                {
                    LabMS.Common.JShelper.JSAlert(Page, "err", "申请开始时间大于结束时间!");
                    return;
                }
            }
            if (string.IsNullOrEmpty(tb_StudentIDs.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "申请人不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(Contactor.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "联系人不能为空!");
                return;
            }
            if (string.IsNullOrEmpty(ContactPhone.Text.Trim()))
            {
                LabMS.Common.JShelper.JSAlert(Page, "err", "联系人的联系电话不能为空!");
                return;
            }

            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
            Regex re = new Regex(strRegex);
            if (!string.IsNullOrEmpty(ContactEmail.Text.Trim()))
            {
                if (!re.IsMatch(ContactEmail.Text.Trim()))
                {
                    LabMS.Common.JShelper.JSAlert(Page, "err", "联系人的EMail地址格式不正确!");
                    return;
                }
            }
            if (!string.IsNullOrEmpty(TeacherEmail.Text.Trim()))
            {
                if (!re.IsMatch(TeacherEmail.Text.Trim()))
                {
                    LabMS.Common.JShelper.JSAlert(Page, "err", "指导老师的EMail地址格式不正确!");
                    return;
                }
            }

            int temp = 0;
            int Index = int.Parse(tb_EIndex.Value);
            for (int i = 0; i < Index; i++)
            {
                if (!string.IsNullOrEmpty(Request.Form["name" + i + ""]))
                {
                    if (string.IsNullOrEmpty(Request.Form["num" + i + ""]))
                    {
                        LabMS.Common.JShelper.JSAlert(Page, "err", "所需仪器数量不能为空!");
                        return;
                    }
                    else
                    {
                        if (!int.TryParse(Request.Form["num" + i + ""], out temp))
                        {
                            LabMS.Common.JShelper.JSAlert(Page, "err", "所需仪器数量必须为数字!");
                            return;
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request.Form["num" + i + ""]))
                    {
                        LabMS.Common.JShelper.JSAlert(Page, "err", "所需仪器名称不能为空!");
                        return;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(Request.Form["intro" + i + ""]))
                        {
                            LabMS.Common.JShelper.JSAlert(Page, "err", "所需仪器名称不能为空!");
                            return;
                        }
                    }
                }
            }
            Index = int.Parse(tb_ConsumpIndex.Value);
            for (int i = 0; i < Index; i++)
            {
                if (!string.IsNullOrEmpty(Request.Form["consumpname" + i + ""]))
                {
                    if (string.IsNullOrEmpty(Request.Form["consumpnum" + i + ""]))
                    {
                        LabMS.Common.JShelper.JSAlert(Page, "err", "所需低耗品数量不能为空!");
                        return;
                    }
                    else
                    {
                        if (!int.TryParse(Request.Form["consumpnum" + i + ""], out temp))
                        {
                            LabMS.Common.JShelper.JSAlert(Page, "err", "所需低耗品数量必须为数字!");
                            return;
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Request.Form["consumpnum" + i + ""]))
                    {
                        LabMS.Common.JShelper.JSAlert(Page, "err", "所需低耗品名称不能为空!");
                        return;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(Request.Form["consumpintro" + i + ""]))
                        {
                            LabMS.Common.JShelper.JSAlert(Page, "err", "所需低耗品名称不能为空!");
                            return;
                        }
                    }
                }
            }
            #endregion
            LabMS.BLL.PersonalProject projectinfo = new LabMS.BLL.PersonalProject();
            LabMS.Model.PersonalProject project = new LabMS.Model.PersonalProject();

            int ProjectID = int.Parse(Request.QueryString["ProjectID"]);
            project.ProjectID = ProjectID;
            project.ProjectName = ProjectName.Text.Trim();
            project.PlanHours = int.Parse(PlanHours.Text.Trim());
            project.AppcationLabID = int.Parse(ddlApplyLab.SelectedValue.Trim());

            DateTime tempTime = new DateTime();
            if (DateTime.TryParse(ApplyTimeMin.Text.Trim(), out tempTime))
            {
                project.ApplicationStartTime = tempTime;
            }
            if (DateTime.TryParse(ApplyTimeMax.Text.Trim(), out tempTime))
            {
                project.ApplicationEndTime = tempTime;
            }

            LabMS.Model.SysSetting msys = new LabMS.Model.SysSetting();
            ExtendBLL.SysSetting extendsys = new ExtendBLL.SysSetting();
            msys = extendsys.GetCurrentSetting();
            project.SYear = msys.CurrentYear;
            project.Semester = msys.CurrentSemester;

            project.Contactor = Contactor.Text.Trim();
            project.ContactorClass = ContactorClass.Text.Trim();
            project.ContactorEmail = ContactEmail.Text.Trim();
            project.ContactorPhone = ContactPhone.Text.Trim();

            project.Teacher = Teacher.Text.Trim();
            project.TeacherTitle = TeacherTitle.Text.Trim();
            project.TeacherEmail = TeacherEmail.Text.Trim();
            project.TeacherPhone = TeacherPhone.Text.Trim();

            project.ApplicationReason = ApplyReason.Text.Trim();
            project.ProjectStatus = "1";//状态为未申请(status=1)
            string strAlertContent = "保存成功!";
            if (((Button)sender).ID == "btnApply")
            {
                strAlertContent = "申请成功!";
                project.ProjectStatus = "2";
            }

            //添加申请人
            string[] array = tb_StudentIDs.Text.Split(',');
            List<string> lsIDs = new List<string>();

            lsIDs.Add(array[0]);

            foreach (string item in array)
            {
                int Count = 0;
                foreach (string Pr in lsIDs)
                {
                    if (item != Pr)
                    {
                        Count++;
                    }
                }
                if (Count == lsIDs.Count)
                {
                    lsIDs.Add(item);
                }
            }

            try
            {
                projectinfo.Update(project);
            } 
            catch (Exception ex)
            {
                lbErr.Visible = true;
                lbErr.Text = ex.Message;
                return;
            }
           
            if (!array[0].Equals(""))
            {
                LabMS.BLL.PersonalProjApp applicantinfo = new LabMS.BLL.PersonalProjApp();
                LabMS.Model.PersonalProjApp applicant = new LabMS.Model.PersonalProjApp();
                List<LabMS.Model.PersonalProjApp> applicantList = new List<LabMS.Model.PersonalProjApp>();

                string str = " PersonalProjID=" + ProjectID;
                applicantList = applicantinfo.GetModelList(str);
                try
                {
                    foreach (LabMS.Model.PersonalProjApp a in applicantList)
                    {
                        applicantinfo.Delete(a.ID);
                    }

                    for (int i = 0; i < lsIDs.Count; i++)
                    {
                        applicant.ApplicantID = int.Parse(lsIDs[i]);
                        applicant.PersonalProjID = ProjectID;
                        applicantinfo.Add(applicant);
                    }
                }
                catch (Exception ex)
                {
                    lbErr.Visible = true;
                    lbErr.Text = ex.Message;
                    return;
                }
            }
            
            //删除对应的仪器和低耗品
            LabMS.BLL.PersonalProjConsume consumeinfo = new PersonalProjConsume();
            LabMS.Model.PersonalProjConsume consume = new LabMS.Model.PersonalProjConsume();
            List<LabMS.Model.PersonalProjConsume> consumeList = new List<LabMS.Model.PersonalProjConsume>();
            string strSql = " PersonalProjID=" + ProjectID;
            consumeList = consumeinfo.GetModelList(strSql);
            try
            {
                foreach (LabMS.Model.PersonalProjConsume c in consumeList)
                {
                    consumeinfo.Delete(c.ID);
                }
            }
            catch(Exception ex)
            {
                lbErr.Visible = true;
                lbErr.Text = ex.Message;
                return;
            }
            //添加仪器
            int EquipIndex = int.Parse(tb_EIndex.Value);           

            for (int i = 0; i < EquipIndex; i++)
            {
                string EquipName = "";
                int EquipNum = 0;
                string Introduction = "";
                try
                {
                    EquipName = Request.Form["name" + i + ""];
                    EquipNum = int.Parse(Request.Form["num" + i + ""]);
                    Introduction = Request.Form["intro" + i + ""];

                    consume.EquipName = EquipName;
                    consume.EquipNum = EquipNum;
                    consume.EquipType = 1;
                    consume.Introduction = Introduction;
                    consume.PersonalProjID = ProjectID;

                    consumeinfo.Add(consume);
                }
                catch { }
            }

            //添加低耗品
            int ConsumpIndex = int.Parse(tb_ConsumpIndex.Value);
            for (int i = 0; i < ConsumpIndex; i++)
            {
                string ConsumpName = "";
                int ConsumpNum = 0;
                string ConsumpIntro = "";
                try
                {
                    ConsumpName = Request.Form["consumpname" + i + ""];
                    ConsumpNum = int.Parse(Request.Form["consumpnum" + i + ""]);
                    ConsumpIntro = Request.Form["consumpintro" + i + ""];

                    consume.EquipName = ConsumpName;
                    consume.EquipNum = ConsumpNum;
                    consume.EquipType = 2;
                    consume.Introduction = ConsumpIntro;
                    consume.PersonalProjID = ProjectID;

                    consumeinfo.Add(consume);
                }
                catch { }
            }
            LabMS.Common.JShelper.JSAlertAndRedirect(Page, "AddSuccess", strAlertContent, "ListPersonalProject.aspx");
        }
    }
}
